package com.jrx.anytxn.customer.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.dto.customer.CmLimitAdjustLogRes;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.customer.entity.CmCustomerLimitInfo;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.entity.CmLimitAdjustLog;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerFirstLevelMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerLimitInfoMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmCustomerSecondLevelMapper;
import com.jrx.anytxn.customer.mapper.ext.ExtCmLimitAdjustLogMapper;
import com.jrx.anytxn.customer.service.IAdjustLimitDetailService;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.param.entity.BtLimitAdjustInfo;
import com.jrx.anytxn.param.entity.TlBatchAdjustLimit;
import com.jrx.anytxn.param.mapper.ext.ExtBtLimitAdjustInfoMapper;
import com.jrx.anytxn.param.mapper.ext.ExtTlBatchAdjustLimitMapper;
import com.jrx.anytxn.sharding.pojo.entity.CacheMapping;
import com.jrx.anytxn.sharding.service.ICacheMappingService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class AdjustLimitDetailServiceImpl implements IAdjustLimitDetailService {

    private static Logger logger = LoggerFactory.getLogger(AdjustLimitDetailServiceImpl.class);

    @Resource
    private ExtCmCustomerSecondLevelMapper extCmCustomerSecondLevelMapper;
    @Autowired(required = false)
    private ICacheMappingService cacheMappingService;
    @Resource
    private ExtCmLimitAdjustLogMapper extCmLimitAdjustLogMapper;
    @Autowired
    private ICustomerService customerService;
    @Resource
    private ExtBtLimitAdjustInfoMapper extBtLimitAdjustInfoMapper;
    @Resource
    private ExtTlBatchAdjustLimitMapper extTlBatchAdjustLimitMapper;
    @Resource
    private ExtCmCustomerLimitInfoMapper extCmCustomerLimitInfoMapper;
    @Resource
    private ExtCmCustomerFirstLevelMapper extCmCustomerFirstLevelMapper;



    @Override
    public TxnPage<CmLimitAdjustLogRes> findAllPageByTenantId(Integer pageNum, Integer pageSize, String customerId, String idNumber,String tenantId) throws TxnException {
        Page<CmLimitAdjustLogRes> page;

        List<CmLimitAdjustLog> cmLimitAdjustLogList;

        if(StringUtils.isBlank(customerId) && StringUtils.isBlank(idNumber)){
            page = PageHelper.startPage(pageNum, pageSize);
            //全部记录查询
            cmLimitAdjustLogList = extCmLimitAdjustLogMapper.selectByTenIdAndNotAdjustType(tenantId,CustomerConstant.ADJUST_TYPE_3);
        }else{
            //按照筛选条件查询
            if(StringUtils.isNotBlank(idNumber)){
                CacheMapping cacheMapping = cacheMappingService.selectFromCacheByIdNumber(tenantId, idNumber, true);
                if(null == cacheMapping){
                    logger.error("客户不存在");
                    throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getMsg());
                }
                customerId = cacheMapping.getCustomerId();
            }

            CmCustomerSecondLevel secondLevelCond = new CmCustomerSecondLevel();
            secondLevelCond.setCustomerId(customerId);
            secondLevelCond.setTenantId(tenantId);
            List<CmCustomerSecondLevel> secondLevels = extCmCustomerSecondLevelMapper.selectByCondition(secondLevelCond);
            if(CollectionUtils.isEmpty(secondLevels)){
                logger.error("客户不存在");
                throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getMsg());
            }

            page = PageHelper.startPage(pageNum, pageSize);

            cmLimitAdjustLogList = extCmLimitAdjustLogMapper.selectByTenIdAndCusIdAndNotAdjustType(tenantId,customerId, CustomerConstant.ADJUST_TYPE_3);
        }

        if(CollectionUtils.isEmpty(cmLimitAdjustLogList)){
            logger.error("查询客户调额明细为空");
            throw new TxnBizException(TxnRespCode.NO_DATA.getCode(), TxnRespCode.NO_DATA.getUserTips());
        }
        List<CmLimitAdjustLogRes> adjustLimitRecordResList = new ArrayList<>();
        for(CmLimitAdjustLog log : cmLimitAdjustLogList){
            CmLimitAdjustLogRes res = BeanMapping.copy(log,CmLimitAdjustLogRes.class);
            //查询客户一级信息
            CmCustomerFirstLevel cmCustomerFirstLevel = extCmCustomerFirstLevelMapper.selectFirstLevelByOrgIdAndCusId(log.getCustomerId(), log.getOrganizationId(), log.getTenantId());
            if(null != cmCustomerFirstLevel){
                res.setChineseName(cmCustomerFirstLevel.getChineseName());
                res.setIdNumber(cmCustomerFirstLevel.getIdNumber());
            }
            //查询客户二级信息
            CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(log.getCustomerId(),log.getChannel(),log.getTenantId());
            if(null != secondLevel){
                res.setMobile(secondLevel.getMobile());
            }

            //获取文件名 只有批量调额需要查文件名
            if(res.getDataSource() != null && res.getDataSource().equals(CustomerConstant.DATASOURCE_1)){
                BtLimitAdjustInfo btLimitAdjustInfo = extBtLimitAdjustInfoMapper.selectByTenantIdAndSeqNo(log.getTenantId(),log.getSeqNo());
                if(null != btLimitAdjustInfo){
                    TlBatchAdjustLimit tlBatchAdjustLimit = extTlBatchAdjustLimitMapper.selectByBatchIdAndTenantId(btLimitAdjustInfo.getTenantId(),btLimitAdjustInfo.getBatchId());
                    if(null != tlBatchAdjustLimit){
                        res.setFileName(tlBatchAdjustLimit.getFilePath());
                    }
                }
            }
            //获取额度生效失败时间
            CmCustomerLimitInfo cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectByTenIdAndCusIdAndLimitId(log.getTenantId(),log.getCustomerId(),log.getLimitId());
            if(null != cmCustomerLimitInfo){
                res.setLimitEffectiveDate(cmCustomerLimitInfo.getLimitEffectiveDate());
                res.setLimitExpiryDate(cmCustomerLimitInfo.getLimitExpiryDate());
            }


            if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_0)){
                if(log.getDataSource().equals(CustomerConstant.DATASOURCE_1)){
                    res.setAdjustType("批量调额");
                }else{
                    res.setAdjustType("单笔调额");
                }
            }else if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_1)){
                res.setAdjustType("单笔冻结");
            }else if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_2)){
                res.setAdjustType("单笔解冻");
            }

            if(log.getResult().equals(CustomerConstant.SUCCESS)){
                res.setResult("成功");
            }else{
                res.setResult("失败");
            }
            adjustLimitRecordResList.add(res);
        }

        return new TxnPage<>(pageNum, pageSize, page.getTotal(), adjustLimitRecordResList);
    }

    @Override
    public CmLimitAdjustLogRes findByTenIdAndCustId(String tenantId, String customerId, Long id) throws TxnException {
        CmLimitAdjustLog log = extCmLimitAdjustLogMapper.selectByTenIdAndCusIdAndId(tenantId,customerId,id);
        CmLimitAdjustLogRes res = BeanMapping.copy(log,CmLimitAdjustLogRes.class);
        //查询客户二级信息
        CmCustomerSecondLevel secondLevel = extCmCustomerSecondLevelMapper.selectByCustomerIdAndChannel(log.getCustomerId(),log.getChannel(),log.getTenantId());
        if(null != secondLevel){
            res.setMobile(secondLevel.getMobile());
        }

        //查询客户一级信息
        CmCustomerFirstLevel cmCustomerFirstLevel = extCmCustomerFirstLevelMapper.selectFirstLevelByOrgIdAndCusId(log.getCustomerId(), log.getOrganizationId(), log.getTenantId());
        if(null != cmCustomerFirstLevel){
            res.setChineseName(cmCustomerFirstLevel.getChineseName());
            res.setIdNumber(cmCustomerFirstLevel.getIdNumber());
        }

        //获取文件名 只有批量调额需要查文件名
        if(res.getDataSource() != null && res.getDataSource().equals(CustomerConstant.DATASOURCE_1)){
            BtLimitAdjustInfo btLimitAdjustInfo = extBtLimitAdjustInfoMapper.selectByTenantIdAndSeqNo(log.getTenantId(),log.getSeqNo());
            if(null != btLimitAdjustInfo){
                TlBatchAdjustLimit tlBatchAdjustLimit = extTlBatchAdjustLimitMapper.selectByBatchIdAndTenantId(btLimitAdjustInfo.getTenantId(),btLimitAdjustInfo.getBatchId());
                if(null != tlBatchAdjustLimit){
                    res.setFileName(tlBatchAdjustLimit.getFilePath());
                }
            }
        }
        //获取额度生效失败时间
        CmCustomerLimitInfo cmCustomerLimitInfo = extCmCustomerLimitInfoMapper.selectByTenIdAndCusIdAndLimitId(log.getTenantId(),log.getCustomerId(),log.getLimitId());
        if(null != cmCustomerLimitInfo){
            res.setLimitEffectiveDate(cmCustomerLimitInfo.getLimitEffectiveDate());
            res.setLimitExpiryDate(cmCustomerLimitInfo.getLimitExpiryDate());
        }

        if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_0)){
            if(log.getDataSource().equals(CustomerConstant.DATASOURCE_1)){
                res.setAdjustType("批量调额");
            }else{
                res.setAdjustType("单笔调额");
            }
        }else if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_1)){
            res.setAdjustType("单笔冻结");
        }else if(log.getAdjustType().equals(CustomerConstant.ADJUST_TYPE_2)){
            res.setAdjustType("单笔解冻");
        }

        if(log.getResult().equals(CustomerConstant.SUCCESS)){
            res.setResult("成功");
        }else{
            res.setResult("失败");
        }
        return res;
    }
}